# 1. 读取 contacts.txt 文件并处理格式错误
contacts = []
try:
    with open("contacts.txt", "r", encoding="utf-8") as f:
        for line_num, line in enumerate(f, 1):  # 记录行号，方便排查错误
            line = line.strip()  # 去除换行和首尾空格
            if not line:  # 跳过空行
                continue
            # 按空格分割，确保能拆分成3个字段
            parts = line.split()
            if len(parts) != 3:
                print(
                    f"警告：第{line_num}行格式错误（需3个字段，空格分隔），已跳过 -> {line}"
                )
                continue
            name, gender, email = parts
            contacts.append((name, gender, email))
except FileNotFoundError:
    print("错误：未找到 contacts.txt 文件，请确认文件存在")
    exit(1)  # 终止程序
except Exception as e:
    print(f"读取文件时出错：{e}")
    exit(1)


# 2. 定义排序规则：先按域名（126.com 在前），再按用户名
def sort_key(item):
    email = item[2]
    # 处理邮箱格式错误（不含@符号）
    if "@" not in email:
        print(f"警告：邮箱格式错误（缺少@） -> {email}，已将其排在最后")
        return (2, email)  # 权重2，确保排在最后
    username, domain = email.split("@", 1)  # 只分割一次，避免邮箱含多个@
    # 域名排序：126.com 在前，163.com 在后，其他域名最后
    if domain == "126.com":
        domain_weight = 0
    elif domain == "163.com":
        domain_weight = 1
    else:
        domain_weight = 2  # 其他域名权重最高，排在最后
    return (domain_weight, username)


# 3. 按规则排序
contacts_sorted = sorted(contacts, key=sort_key)

# 4. 生成 emails.txt
try:
    with open("emails.txt", "w", encoding="utf-8") as f:
        for name, gender, email in contacts_sorted:
            salutation = "女士" if gender == "女" else "先生"
            f.write(f"to: <{email}>\n")
            f.write(f"尊敬的{name}{salutation}，您的会员资格即将到期，请及时续费。\n")
            f.write("---\n")
    print("处理完成，已生成 emails.txt")
except Exception as e:
    print(f"写入文件时出错：{e}")
